import Vue from 'vue'
import VueRouter from 'vue-router'
import Test from '@/views/Test'
import Register from '@/views/Register'
import Login from '@/views/Login'
import UserInfo from '@/views/UserInfo'
import EditInfo from '@/views/EditInfo'
Vue.use(VueRouter)

const routes = [
  {
    path: '/test',
    component: Test,
    meta: { isToken: false }
  },
  {
    path: '/register',
    component: Register,
    meta: { isToken: false }
  },
  {
    path: '/login',
    component: Login,
    meta: { isToken: false }
  },
  {
    path: '/userinfo',
    component: UserInfo,
    meta: { isToken: true }
  },
  {
    path: '/editinfo',
    component: EditInfo,
    meta: { isToken: true }
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // to 访问的路径 from 从哪来 next 响应路径
  if (to.meta.isToken === false) {
    return next()
  } else {
    const token = window.sessionStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
